package com.vfa.test;

import java.util.ArrayList;

import com.vfa.vocaburay.R;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class ListCatagory extends Activity{

	private int ID_LISTITEMCATA = 1;
	
	private ListView listviewcata;
	QuestionData data;
	ArrayList<CatagoryE> arraylist;
	
	CatagoryE catagoryitem;
	CatagoryAdapter adapter;

	private String[] listarr;
	//
	private LinearLayout linerlayout, linercontentbtn;
	private TextView tv_titleview, tvnumofcatagory;
	private Button btnaddnewcatagory;
	
	private static final int DIALOG_NEW_CATAGORY = 0;
	private static final int DIALOG_DELETE_CATAGORY = 1;
	private static final int DIALOG_UPDATE_CATAGORY = 2;
	private static final int DIALOG_LIST = 3;
	
	CharSequence[] items = {"Delete", "Update"};
	
	private String dialogmessage = "";
	private int cataid;
	private String catagoryname;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.list_catagorys);
		linerlayout = (LinearLayout)findViewById(R.id.liner_listCatagory);
		btnaddnewcatagory = (Button)findViewById(R.id.btn_newcatagory);
		//create view item;
		data = new QuestionData(this);
		arraylist = new ArrayList<CatagoryE>();
		
		
		getCatagory();
		
		//create listview show list catagory 
		listviewcata = new ListView(this);
		listviewcata.setId(ID_LISTITEMCATA);
		
		listviewcata.setAdapter(adapter);
		listviewcata.setOnItemClickListener(new AdapterView.OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> adapterView, View arg1, int position,
					long arg3) {
				//long rowIndex = adapterView.getItemIdAtPosition(position)  ;
				//catagoryitem = arraylist.get(position);
				Intent intent = new Intent(getApplicationContext(), ListQuestion.class);
				intent.putExtra("catagoryname", arraylist.get(position).getCatagoryName());
				intent.putExtra("flagactivity", 1);
				startActivity(intent);
				//ListCatagory.this.finish();
			}
		});
		
		listviewcata.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {

			@Override
			public boolean onItemLongClick(AdapterView<?> adapterView, View arg1,
					int position, long arg3) {
				cataid = arraylist.get(position).getCatagoryId();
				catagoryname = arraylist.get(position).getCatagoryName();
				showDialog(DIALOG_LIST);
				return false;
			}
		});
		
		
		//create button
		btnaddnewcatagory.setOnClickListener(btn_addNewCatagory);

		//add widget to linerlayout
		//linerlayout.addView(btnaddnewcatagory,0);
		linerlayout.addView(listviewcata,1);
		
	}
	
	private android.view.View.OnClickListener btn_addNewCatagory = new android.view.View.OnClickListener() {
		
		@Override
		public void onClick(View v) {
			showDialog(DIALOG_NEW_CATAGORY);
		}
	};
	
	
	
	@Override
	protected void onRestart() {
		// TODO Auto-generated method stub
		super.onRestart();
		System.out.println("on Restart !");
		
		getCatagory();
   		listviewcata.setAdapter(adapter);
	}
	
	

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		System.out.println("on Pause !");
	}



	@Override
	protected void onPostResume() {
		// TODO Auto-generated method stub
		super.onPostResume();
		System.out.println("on PostResume !");
	}



	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		System.out.println("on ReSume !");
	}



	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
		System.out.println("on Start !");
	}



	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
		System.out.println("on Stop !");
	}



	private void getCatagory(){
		
		arraylist = data.getAllCatagory();
		adapter = new CatagoryAdapter(this, R.layout.item_catagory, arraylist);
		adapter.notifyDataSetChanged();
		System.out.println(adapter.getCount());
	}
	
	@Override
	protected Dialog onCreateDialog(int id) {
		// TODO Auto-generated method stub
		
		 AlertDialog.Builder dialog =new AlertDialog.Builder(this);
		switch (id) {
		
		case DIALOG_LIST:
			dialog.setTitle("Please Select option!");
			dialog.setSingleChoiceItems(items, -1, new DialogInterface.OnClickListener() {					
				@Override
				public void onClick(DialogInterface dialog, int which) {
					
						if (items[which].toString().equals("Delete")) {
							dialogmessage ="Do you want to delete this level ?";
							showDialog(DIALOG_DELETE_CATAGORY);
						}
						else if (items[which].toString().equals("Update")) {
							dialogmessage ="Do you want to update this level ?";
							showDialog(DIALOG_UPDATE_CATAGORY);
						}
						dialog.dismiss();
					}
					
			});
			AlertDialog alert0 = dialog.create();
			return alert0;
			//alert0.show();
		
			//break;
			
		case DIALOG_NEW_CATAGORY:
			 LayoutInflater factory1 = LayoutInflater.from(this);
	            final View textEntryView1 = factory1.inflate(R.layout.inputcategory, null);
	            return new AlertDialog.Builder(ListCatagory.this)
	                   .setTitle("Input new level")
	                .setView(textEntryView1)
	                .setPositiveButton("Add", new DialogInterface.OnClickListener() {
	                    public void onClick(DialogInterface dialog, int whichButton) {
	                    	EditText etNewCategory = (EditText) textEntryView1.findViewById(R.id.etNewCategory);
	                    	String strNewCatagory =  String.valueOf(etNewCategory.getText()).trim();
	                        // them catalog
	                    	if(strNewCatagory != "" || strNewCatagory.length() >0){
	                    		try {
	                    			data.InsertCatagory(strNewCatagory);
								} catch (Exception e) {
									// TODO: handle exception
								}
	                    		
	                    		getCatagory();
	                    		
	                    		listviewcata.setAdapter(adapter);
	                    		
	                    		etNewCategory.setText("");
	                    		dialog.dismiss();
	                    	}
	                    	else{
	                    		Toast.makeText(getBaseContext(), "Please input value!", Toast.LENGTH_SHORT).show();
	                    	}
	                    	
	                    }
	                })
	                .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
	                    public void onClick(DialogInterface dialog, int whichButton) {

	                        dialog.dismiss();
	                    }
	                })
	                .create();
	            
	     case DIALOG_DELETE_CATAGORY:
	    	 dialog.setTitle(" Notice! ");
				dialog.setMessage(dialogmessage);
				dialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
					
					@Override
					public void onClick(DialogInterface dialog, int which) {
						try {
							data.DeleteCatagory(cataid);
							data.DeleteQuestionInCata(catagoryname);
							
						} catch (Exception e) {
							// TODO: handle exception
						}
						
                   		getCatagory();
                   		listviewcata.setAdapter(adapter);
					}
				});
				dialog.setNegativeButton("No", new DialogInterface.OnClickListener() {
					
					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
					}
				});
				AlertDialog alert1 = dialog.create();
				return alert1;
				//alert1.show();
				//break;
			
		
		case DIALOG_UPDATE_CATAGORY:
		 LayoutInflater factoryupdate = LayoutInflater.from(this);
           final View textEntryView = factoryupdate.inflate(R.layout.inputcategory, null);
       		final EditText etNewCategory = (EditText) textEntryView.findViewById(R.id.etNewCategory);
       			etNewCategory.setText(catagoryname);
           return new AlertDialog.Builder(ListCatagory.this)
                  .setTitle("Change level to update")
               .setView(textEntryView)
               .setPositiveButton("Ok", new DialogInterface.OnClickListener() {
                   public void onClick(DialogInterface dialog, int whichButton) {
                   
                   	String strNewCatagory =  String.valueOf(etNewCategory.getText()).trim();
                       // them catalog
                   	if(strNewCatagory != "" || strNewCatagory.length() >0){
                   		try {
                   			data.UpdateCatagory(cataid, strNewCatagory);
                   			Toast.makeText(getApplicationContext(), "Insert level "+ strNewCatagory+ "success !", Toast.LENGTH_SHORT).show();
						} catch (Exception e) {
							Toast.makeText(getApplicationContext(), "Can not Insert level "+ strNewCatagory, Toast.LENGTH_SHORT).show();
						}
                   		getCatagory();
                   		listviewcata.setAdapter(adapter);
                   		etNewCategory.setText("");
                   		dialog.dismiss();
                   	}
                   	else{
                   		Toast.makeText(getBaseContext(), "Please input value!", Toast.LENGTH_SHORT).show();
                   	}
                   }
               })
               .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                   public void onClick(DialogInterface dialog, int whichButton) {
                	   etNewCategory.setText("");
                       dialog.dismiss();
                   }
               })
               .create();
		}
		return super.onCreateDialog(id);
	}
	
}
